const router = require('koa-router')()
const sequelize = require('../../dbHelper/db')
const { sys_menu: MenuModel } = require('../../dbHelper/db').models
const { Op } = require('sequelize')
const { hasParamsFiled, toTreeByRecursion } = require('../../utils')

router.prefix('/menu')

router.get('/getMenuList', async(ctx) => {
  const query = ctx.request.query

  const where = {}

  if (hasParamsFiled(query.menu_name)) {
    where.menu_name = {
      [Op.substring]: query.menu_name
    }
  }

  if (hasParamsFiled(query.status)) {
    where.status = query.status
  }

  const menuList = await MenuModel.findAll({
    where
  })

  ctx.body = {
    code: 0,
    data: menuList,
    msg: 'ok'
  }
})

router.get('/getTreeMenu', async(ctx) => {
  const query = ctx.request.query

  const where = {}

  if (hasParamsFiled(query.status)) {
    where.status = query.status
  }

  const menuList = await MenuModel.findAll({ where })

  const allList = [...menuList]
  let parentIdNoneValue = 0

  if (hasParamsFiled(query.add_top) && Boolean(+query.add_top)) {
    allList.unshift({
      parent_id: -1,
      menu_id: 0,
      menu_name: '主菜单'
    })
    parentIdNoneValue = -1
  }

  const result = toTreeByRecursion(allList, 'menu_id', 'parent_id', parentIdNoneValue, 'children')

  ctx.body = {
    code: 0,
    data: result,
    msg: 'ok'
  }
})

router.get('/getRouters', async(ctx) => {
  const where = {
    menu_type: {
      [Op.ne]: 'F'
    },
    status: 0
  }

  const menuList = await MenuModel.findAll({ where, order: [
    ['order_num', 'ASC']
  ] })

  ctx.body = {
    code: 0,
    data: menuList,
    msg: 'ok'
  }
})

router.post('/addMenu', async(ctx) => {
  // 请求参数校验
  ctx.verifyParams({
    parent_id: { type: 'number', required: true },
    menu_name: { type: 'string', required: true },
    order_num: { type: 'number', required: true },
    menu_type: { type: 'enum', values: ['M', 'C', 'F'] }
  })

  const params = ctx.request.body

  let objMenu = await MenuModel.findOne({
    where: {
      menu_name: params.menu_name
    }
  })

  if (objMenu) {
    ctx.body = {
      code: -1,
      msg: '菜单名重复，创建失败！'
    }
  } else {
    objMenu = await MenuModel.create({
      parent_id: params.parent_id,
      menu_name: params.menu_name,
      order_num: params.order_num,
      menu_type: params.menu_type,
      path: params.path,
      component: params.component,
      is_frame: params.is_frame,
      is_cache: params.is_cache,
      visible: params.visible,
      status: params.status,
      perms: params.perms,
      icon: params.icon
    })

    ctx.body = {
      code: 0,
      msg: '创建成功！',
      data: objMenu
    }
  }
})

router.put('/modifyMenu', async(ctx) => {
  // 请求参数校验
  ctx.verifyParams({
    menu_id: { type: 'number', required: true }
  })

  const params = ctx.request.body

  const otherMenu = await MenuModel.findOne({
    where: {
      menu_id: {
        [Op.ne]: params.menu_id
      },
      [Op.or]: {
        menu_name: params.menu_name
      }
    }
  })

  if (otherMenu) {
    ctx.body = {
      code: -1,
      msg: '部门名重复，不能修改！'
    }
  } else {
    await MenuModel.update({
      parent_id: params.parent_id,
      menu_name: params.menu_name,
      order_num: params.order_num,
      menu_type: params.menu_type,
      path: params.path,
      component: params.component,
      is_frame: params.is_frame,
      is_cache: params.is_cache,
      visible: params.visible,
      status: params.status,
      perms: params.perms,
      icon: params.icon
    }, {
      where: {
        menu_id: params.menu_id
      }
    })

    let [sub_menu_ids] = await sequelize.query(`
      select menu_id from (
        select t1.menu_id,
        if(find_in_set(parent_id, @pids) > 0, @pids \:= concat(@pids, ',', menu_id), 0) as ischild
        from (
         select menu_id,parent_id from sys_menu t order by parent_id, menu_id
        ) t1,
        (select @pids \:= :pid) t2
      ) t3 where ischild != 0`, {
      replacements: {
        pid: params.menu_id
      }
    })

    if (Array.isArray(sub_menu_ids) && sub_menu_ids.length > 0) {
      sub_menu_ids = sub_menu_ids.map(menu => menu.menu_id)
      await MenuModel.update({
        status: params.status,
        visible: params.visible
      }, {
        where: {
          menu_id: {
            [Op.in]: sub_menu_ids
          }
        }
      })
    }

    ctx.body = {
      code: 0,
      msg: '修改成功！',
      sub_menu_ids
    }
  }
})

router.delete('/deleteMenu', (ctx) => {
  // const query = ctx.request.query
  //
  // if (query.dept_id === undefined) {
  //   ctx.body = {
  //     code: -1,
  //     msg: '参数错误'
  //   }
  //   return
  // }
  //
  // DeptModel.update({
  //   del_flag: 2
  // }, {
  //   where: {
  //     dept_id: query.dept_id
  //   }
  // })
  //
  // ctx.body = {
  //   code: 0,
  //   msg: '删除成功！'
  // }
})

module.exports = router
